package com.example.redissession.dlm.impl;

import com.example.redissession.dlm.DLM;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author: cph
 * @date: 2022/3/18 17:49
 */
@Slf4j
@Component("redisDLM")
public class RedisDLMImpl implements DLM {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    @Qualifier("unlock")
    private RedisScript<Boolean> unlockScript;


    @Override
    public boolean lock(String key, String value, Long timeout, TimeUnit unit) {
        log.info("redis start lock");
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        Boolean ifAbsent = opsForValue.setIfAbsent(key, value, timeout, unit);
        if (ifAbsent == null) {
            log.warn("redis lock failure");
            return false;
        }
        return ifAbsent;
    }

    @Override
    public void unLock(String key, String value) {
        log.info("redis start unlock");
        redisTemplate.execute(unlockScript, Collections.singletonList(key), value);
    }
}
